<template>
	<el-row :gutter="20">
		<el-col :span="6">

			<el-dropdown class="dropdown-font" @command="handleCommand">
				<span class="el-dropdown-link">
					{{ bank.name }}
					<el-icon class="el-icon--right">
						<arrow-down />
					</el-icon>
				</span>
				<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item :command="item.id" v-for="(item, index) in bankList" :key="index">
							{{ item.name }}
						</el-dropdown-item>
					</el-dropdown-menu>
				</template>
			</el-dropdown>
			<el-scrollbar height="100vh">
				<el-tree :default-expand-all="true" node-key="id" highlight-current style="max-width: 600px"
					:data="teamNumData" :props="defaultProps" @node-click="handleNodeClick" />

			</el-scrollbar>
		</el-col>

		<el-col :span="18">
			<el-card>
				<TableSearch :search="state.tableData.search" @search="onSearch" />

				<Table ref="tableRef" v-bind="state.tableData" class="table-demo" @selectionTable="handleSelectionTable"
					@pageChange="onTablePageChange" @sortHeader="onSortHeader">
					<template #header>
						<el-button type="primary" @click="onOpenAddQuestion('add')">新增</el-button>
						<el-button type="primary" @click="batchDelete">批量删除</el-button>
					</template>

					<template #actionCol="{ row }">
						<el-button text size="small" type="primary" @click="handleDetail(row)">查询</el-button>
						<el-button text size="small" type="primary" @click="onOpenEditQuestion('edit', row)">编辑</el-button>
						<el-popconfirm title="确定删除吗？" @confirm="onTableDelRow(row)">
							<template #reference>
								<el-button text size="small" type="primary">删除</el-button>
							</template>
						</el-popconfirm>
					</template>
				</Table>
			</el-card>

			<QuestionDialog  ref="questionDialogRef" @refresh="getTableData"/>
		</el-col>
	</el-row>
	
</template>

<script setup name="question">
import { ArrowDown, Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { onMounted, ref, reactive, computed, defineAsyncComponent } from 'vue'
import { QuestionCategory, QuestionBank, Question,QuestionAnswer } from '/@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
// 引入组件
const QuestionDialog = defineAsyncComponent(() => import('/@/views/question/question/dialog.vue'));

// 定义变量内容
const tableRef = ref();
const state = reactive({
	tableData: {
		// 列表数据（必传）
		data: [],
		// 表头内容（必传，注意格式）
		header: [
			{ key: 'content', colWidth: '', title: '问题内容', type: 'text', isCheck: true },
			{ key: 'teamId', colWidth: '', title: '题目组', type: 'text', isCheck: true },
			{ key: 'answerId', colWidth: '', title: '正确答案id', type: 'text', isCheck: true },
			{ key: 'orderNum', colWidth: '', title: '排序', type: 'text', isCheck: true },
		],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: false, // loading 加载,初始化加载页面是否加载loding动画效果
			isBorder: true, // 是否显示表格边框
			isSerialNo: true, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isOperate: true, // 是否显示表格操作栏
			isShowTool: true,//是否显示表头工具栏
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
		search: [
			{ label: '题目内容', prop: 'content', placeholder: '题目内容', required: false, type: 'input' },
		],
		// 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
		param: {
			pageNum: 1,
			pageSize: 10,
			conditions: []
		},
		//设置页面进入初始化一直使用的参数条件
		initConditions: [],
		// 打印标题
		printName: 'vueNextAdmin 表格打印演示',
	},
});



// 初始化列表数据
const getTableData = async () => {
	state.tableData.config.loading = true;

	await Question.questionsList(state.tableData.param).then(res => {
		if (res.data) {
			state.tableData.data = res.data.list
			state.tableData.config.total = res.data.total
		}
	})
	// 数据总数（模拟，真实从接口取）
	setTimeout(() => {
		state.tableData.config.loading = false;
	}, 500);
}
// 搜索点击时表单回调
const onSearch = (condit) => {
	if (state.tableData.initConditions.length == 0) {
		ElMessage.error("请先选中左侧题目组信息");
		return
	}
	//先进行清除，否则会一直加数组数据
	state.tableData.param.conditions = [];
	state.tableData.param.conditions = [...state.tableData.initConditions, ...condit]
	// tableRef.value.pageReset();
	getTableData()

};

//多选框选中的值
const checkList = ref([]);
//子组件调用的多选回调方法
const handleSelectionTable = (selectlist) => {
	checkList.value = selectlist
}

// 查询当前行详细信息
const handleDetail = (row) => {
	ElMessage.info(row.id);
};

//定义弹出框的ref
const questionDialogRef = ref()
//新增按钮方法
const onOpenAddQuestion =(type)=>{
	questionDialogRef.value.onOpen(type)
}
const onOpenEditQuestion =async (type,row)=>{
	
	let qId = row.id;
	await QuestionAnswer.answerOptionsByQId(qId).then(res=>{
		row.answerList =  res.data
	})
	
	questionDialogRef.value.onOpen(type,row)
}

const closeDialog=()=>{
	getTableData();
}

const batchDelete = () => {
	if (checkList.value.length == 0) {
		ElMessage.error("至少选中一条数据")
	} else {
		ElMessageBox.confirm(
			'是否确认要删除数据?',
			'Warning',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(async () => {
				let idArr = []
				checkList.value.forEach(e => {
					idArr.push(e.id)
				});
				let ids = idArr.join(',')
				console.log(ids);
				await Question.delQuestions(ids).then(res => {
					getTableData();
					//删除接口
					ElMessage({
						type: 'success',
						message: res.data,
					})
					
				})

			})
	}
}

// 删除当前项回调
const onTableDelRow = async (row) => {
	let content = row.content
	await Question.delQuestions(row.id)
	ElMessage.success(`删除${content}成功！`);
	getTableData();
};
// 分页改变时回调
const onTablePageChange = (page) => {

	state.tableData.param.pageNum = page.pageNum;
	state.tableData.param.pageSize = page.pageSize;
	getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data) => {
	state.tableData.header = data;
};


const handleNodeClick = (data) => {
	//没有子节点说明是叶子节点
	if (data.children == null) {
		let conditions = []
		conditions.push({ name: 'teamId', value: data.id })
		state.tableData.initConditions = conditions

		state.tableData.param.conditions = [...state.tableData.initConditions]
		getTableData()
	} else {
		return
	}
}


const defaultProps = {
	children: 'children',
	label: 'label',
}

const handleCommand = (command) => {
	// ElMessage(`click on item ${command}`)
	initCategoryList(command)
}

const bankList = ref([])
const bank = reactive({
	id: '',
	name: ''
})

const initQuestionBankList = async () => {
	await QuestionBank.getAllBankList().then((res) => {
		let data = res.data
		bankList.value = data
		bank.id = data[0] == null ? '' : data[0].id
		bank.name = data[0] == null ? '' : data[0].name
		initCategoryList(bank.id)
	})
}

const teamNumData = ref([])
const initCategoryList = async (id) => {
	await QuestionCategory.getCategoryAndTeamListAndQuestionNum(id).then((res) => {
		teamNumData.value = res.data;
	})
}

onMounted(() => {
	initQuestionBankList()
})

</script>

<style lang="scss" scoped>
.example-showcase .el-dropdown-link {
	cursor: pointer;
	color: #409eff;
	display: flex;
	align-items: center;
}

.dropdown-font {
	margin-top: 10px;
	margin-bottom: 10px;
}

.el-dropdown-link {
	cursor: pointer;
	color: #409eff;
	display: flex;
	align-items: center;
	font-size: 1.5rem;
}
</style>